package DesginFotmat;

import lombok.extern.slf4j.Slf4j;

public class BalkingMode {
    /**
     * 设计模式之犹豫模式，当线程发现有其他线程正在做相同的事时，本线程无需再做，直接返回
     */
    public static void main(String[] args) {
        MonitorThread3 monitorThread3 = new MonitorThread3();
        monitorThread3.start();
    }

}

@Slf4j
class MonitorThread3{
    //监控线程
    private Thread monitorThread;
    //停止标记
    private volatile boolean stop = false;
    //判断是否执行过start方法
    private boolean starting = false;

    //启动监控线程
    public void start(){
        //加锁，防止多线程情况下重复创建监控线程
        synchronized (this){
            if(starting){
                return;
            }
            starting = true;
            monitorThread = new Thread(()->{
                while(true){
                    Thread current = Thread.currentThread();
                    //是否被打断
                    if(stop){
                        log.debug("料理后事");
                        break;
                    }
                    try{
                        Thread.sleep(1000);
                        log.debug("执行监控记录");
                    }catch(InterruptedException e){

                    }
                }
            });
            monitorThread.start();
        }

    }


    //停止监控线程
    public void stop(){
        stop = true;
        monitorThread.interrupt();
    }
}
